﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;

namespace ElValWeb.ValidatorClientAdapters {
    public class OrCompositeValidatorClientAdapter : BaseClientAdapter<OrCompositeValidatorData> {
        
        public OrCompositeValidatorClientAdapter(OrCompositeValidatorData validatorData)
            : base(validatorData) {
        }

        public override IEnumerable<ModelClientValidationRule> GetClientRules(Type ownerType) {
            var resultedMadelClient = new ModelClientValidationRule {
                                                                        ErrorMessage = ValidatorData.GetMessageTemplate(),
                                                                        ValidationType = "orComposite"
                                                                    };
            var anyOfInnerIsEmpty = false;

            //if we don't know one of predicates in or statement
            //all logic can be compromised
            var rulesOverall = new List<IEnumerable<ModelClientValidationRule>>(); 
            

            foreach (var validatorData in ValidatorData.Validators) {
                var rules = ClientAdapterFactory.GetAdapter(validatorData).GetClientRules(ownerType);
                anyOfInnerIsEmpty = (anyOfInnerIsEmpty || (rules.Count() == 0));
                rulesOverall.Add(rules);
            }

            if(anyOfInnerIsEmpty) {
                return new ModelClientValidationRule[]{};
            }

            resultedMadelClient.ValidationParameters["innerValidators"] = rulesOverall;

            return new [] {resultedMadelClient};
        }
    }
}
